package com.jhworks.library.ui;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;


import com.andbase.library.app.base.AbBaseActivity;
import com.andbase.library.utils.AbAppUtil;
import com.jhworks.library.Constant;
import com.jhworks.library.R;
import com.jhworks.library.bean.MediaSelectConfig;

import java.io.File;
import java.util.ArrayList;


public class ImageSelectActivity extends AbBaseActivity
        implements ImageSelectorFragment.Callback {
    protected static final int REQUEST_STORAGE_READ_ACCESS_PERMISSION = 101;


    private ArrayList<String> resultList = new ArrayList<>();
    private Button mSubmitButton;
    private MediaSelectConfig mMediaSelectConfig;

    private static Intent createIntent(Context context, MediaSelectConfig mediaSelectConfig) {
        Intent intent = new Intent(context, ImageSelectActivity.class);
        intent.putExtra(Constant.KEY_MEDIA_SELECT_CONFIG, mediaSelectConfig);
        return intent;
    }

    public static void start(Activity activity, int requestCode, MediaSelectConfig mediaSelectConfig) {
        if (activity == null || activity.isFinishing()) return;

        //检查权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            boolean result =  AbAppUtil.requestPermissions(activity,new String []{
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.CAMERA
            },REQUEST_STORAGE_READ_ACCESS_PERMISSION);
            if(result){
                activity.startActivityForResult(createIntent(activity, mediaSelectConfig), requestCode);
            }
        }else{
            activity.startActivityForResult(createIntent(activity, mediaSelectConfig), requestCode);
        }

    }

    public static void start(Fragment fragment, int requestCode, MediaSelectConfig mediaSelectConfig) {
        if (fragment == null) return;
        final Activity activity = fragment.getActivity();
        if (activity == null || activity.isFinishing()) return;

        //检查权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            boolean result =  AbAppUtil.requestPermissions(activity,new String []{
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.CAMERA
            },REQUEST_STORAGE_READ_ACCESS_PERMISSION);
            if(result){
                activity.startActivityForResult(createIntent(activity, mediaSelectConfig), requestCode);
            }
        }else{
            activity.startActivityForResult(createIntent(activity, mediaSelectConfig), requestCode);
        }

    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == REQUEST_STORAGE_READ_ACCESS_PERMISSION && AbAppUtil.hasAllPermissionsGranted(grantResults)) {
            startActivityForResult(createIntent(this, mMediaSelectConfig), requestCode);
        } else {
            Toast.makeText(this, "应用缺少必要的权限！请点击\"权限\"，打开所需要的权限。", Toast.LENGTH_LONG).show();
            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            intent.setData(Uri.parse("package:" + getPackageName()));
            startActivity(intent);
            finish();
        }

    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        View contentView = View.inflate(this,R.layout.activity_image_select,null);
        setContentView(contentView);

        Toolbar toolbar = (Toolbar)this.findViewById(R.id.toolbar);
        mSubmitButton = (Button)this.findViewById(R.id.commit);

        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setTitle(R.string.select_phone);

        Intent intent = this.getIntent();

        mMediaSelectConfig = intent.getParcelableExtra(Constant.KEY_MEDIA_SELECT_CONFIG);

        //工具栏的颜色
        toolbar.setBackgroundColor(mMediaSelectConfig.getPrimaryColor());
        contentView.setBackgroundColor(mMediaSelectConfig.getPrimaryColor());

        if (mMediaSelectConfig.getSelectMode() == MediaSelectConfig.MODE_MULTI
                && mMediaSelectConfig.getOriginData() != null) {
            resultList = mMediaSelectConfig.getOriginData();
        }

        if (mMediaSelectConfig.getSelectMode() == MediaSelectConfig.MODE_MULTI) {
            updateDoneText(resultList);
            mSubmitButton.setVisibility(View.VISIBLE);
            mSubmitButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (resultList != null && resultList.size() > 0) {
                        // Notify success
                        Intent data = new Intent();
                        data.putStringArrayListExtra(Constant.KEY_EXTRA_RESULT, resultList);
                        setResult(RESULT_OK, data);
                    } else {
                        setResult(RESULT_CANCELED);
                    }
                    finish();
                }
            });
        } else {
            mSubmitButton.setVisibility(View.GONE);
        }

        if (savedInstanceState == null) {
            Bundle bundle = new Bundle();
            bundle.putParcelable(Constant.KEY_MEDIA_SELECT_CONFIG, mMediaSelectConfig);
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.image_grid, Fragment.instantiate(this,
                            ImageSelectorFragment.class.getName(), bundle))
                    .commit();
        }

    }


    private void updateDoneText(ArrayList<String> resultList) {
        int size = 0;
        if (resultList == null || resultList.size() <= 0) {
            mSubmitButton.setText(R.string.mis_action_done);
            mSubmitButton.setEnabled(false);
        } else {
            size = resultList.size();
            mSubmitButton.setEnabled(true);
        }
        mSubmitButton.setText(getString(R.string.mis_action_button_string,
                getString(R.string.mis_action_done), size, mMediaSelectConfig.getMaxCount()));
    }

    @Override
    public void onSingleImageSelected(String path) {
        Intent data = new Intent();
        resultList.add(path);
        data.putStringArrayListExtra(Constant.KEY_EXTRA_RESULT, resultList);
        setResult(RESULT_OK, data);
        finish();
    }

    @Override
    public void onImageSelected(String path) {
        if (!resultList.contains(path)) {
            resultList.add(path);
        }
        updateDoneText(resultList);
    }

    @Override
    public void onImageUnselected(String path) {
        if (resultList.contains(path)) {
            resultList.remove(path);
        }
        updateDoneText(resultList);
    }

    @Override
    public void onCameraShot(File imageFile) {
        if (imageFile != null) {
            // notify system the image has change
            sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(imageFile)));

            Intent data = new Intent();
            resultList.add(imageFile.getAbsolutePath());
            data.putStringArrayListExtra(Constant.KEY_EXTRA_RESULT, resultList);
            setResult(RESULT_OK, data);
            finish();
        }
    }

    @Override
    public void onImageSelectList(ArrayList<String> imageList) {
        if (resultList.size() > 0)
            resultList.clear();
        resultList.addAll(imageList);
        updateDoneText(resultList);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                setResult(RESULT_CANCELED);
                finish();
                return true;
            default:
        }
        return super.onOptionsItemSelected(item);
    }
}
